﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace SBPweb.PROvibe.Shared.Library.Base
{

    public static class IVersionableExtensions
    {

        #region Contains

        public static bool ContainsVersion(this IEnumerable<IVersionable> element, Version version)
        {
            return ContainsVersion<IVersionable>(element, version);
        }

        public static bool ContainsVersion<TSource>(this IEnumerable<TSource> element, Version version)
            where TSource : IVersionable
        {
            return element.Any(x => x.Version == version);
        }

        #endregion

        #region First

        public static IVersionable FirstByVersion(this IEnumerable<IVersionable> element, Version version)
        {
            return FirstByVersion<IVersionable>(element, version);
        }

        public static TResult FirstByVersion<TResult>(this IEnumerable<IVersionable> element, Version version)
            where TResult : IVersionable
        {
            return FirstByVersion<IVersionable, TResult>(element, version);
        }

        public static TResult FirstByVersion<TSource, TResult>(this IEnumerable<TSource> element, Version version)
            where TSource : IVersionable
            where TResult : TSource
        {
            return (TResult)element.FirstOrDefault(x => x.Version.Equals(version));
        }

        #endregion

        #region Where

        public static IEnumerable<IVersionable> WhereVersionIs(this IEnumerable<IVersionable> element, Version version)
        {
            return WhereVersionIs<IVersionable>(element, version);
        }

        public static IEnumerable<TResult> WhereVersionIs<TResult>(this IEnumerable<IVersionable> element, Version version)
            where TResult : IVersionable
        {
            return WhereVersionIs<IVersionable, TResult>(element, version);
        }

        public static IEnumerable<TResult> WhereVersionIs<TSource, TResult>(this IEnumerable<TSource> element, Version version)
            where TSource : IVersionable
            where TResult : TSource
        {
            return element.Where(x => x.Version.Equals(version)).Cast<TResult>().ToList();
        }

        #endregion

    }

}